package com.igrowing.springbootinit.biMQ;

import com.igrowing.springbootinit.common.ErrorCode;
import com.igrowing.springbootinit.exception.BusinessException;
import com.igrowing.springbootinit.manager.AiManager;
import com.igrowing.springbootinit.model.entity.Chart;
import com.igrowing.springbootinit.service.ChartService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Description:    // 类说明
 *
 * @ClassName: biConsume    // 类名，会自动填充
 * @Author: 周天赐        // 创建者
 * @Email: m18879004515@163.com
 * @Date: 2024/4/2 17:21   // 时间
 * @Version: 1.0     // 版本
 */
@Component
@Slf4j
public class BiConsumer {

    @Resource
    private ChartService chartService;

    @Resource
    private AiManager aiManager;

    @SneakyThrows
    @RabbitListener(queues = {BiMqConstant.BI_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("recevieMessage:{}", message);
        if (StringUtils.isBlank(message)) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "消息为空");
        }
        long charId = Long.parseLong(message);
        Chart chart = chartService.getById(charId);
        if (chart == null) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图表不存在");
        }

        //todo 修改状态,处理消息
        Chart updateChar = new Chart();
        updateChar.setId(charId);
        updateChar.setStatus("running");
        boolean result = chartService.updateById(updateChar);
        if (!result) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "更新图表状态失败");
        }

        //todo 获取要传给AI分析的数据
        String finalTarget = buildGoal(chart);

        //todo 调用AI
        String aiResult = aiManager.getAiResult(finalTarget);
        String[] split = aiResult.split("【【【【【");
        if (split.length < 3) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI生成错误");
        }
        //todo 提取图表生成语句和分析结论
        String genChart = split[1];
        String genResult = split[2];

        Chart updateChartResult = new Chart();
        updateChartResult.setId(chart.getId());
        updateChartResult.setGenChart(genChart);
        updateChartResult.setGenResult(genResult);
        // todo 建议定义状态为枚举值
        updateChartResult.setStatus("succeed");
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            handleChartUpdateError(chart.getId(), "更新图表成功状态失败");
        }

        // 消息确认
        channel.basicAck(deliveryTag, false);


    }


    private String buildGoal(Chart chart) {
        //todo 获取用户需求和保存在数据库中的cvs数据
        String goal = chart.getGoal();
        String chartData = chart.getChartData();

        StringBuilder target = new StringBuilder();
        //todo 将用户的需求按格式要求拼接
        target.append("分析需求：").append("\n");
        target.append(goal).append("\n");
        //todo 插入压缩后的cvs数据
        target.append("原始数据：").append("\n");
        target.append(chartData).append("\n");
        String finalTarget = target.toString();

        return finalTarget;
    }


    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus("failed");
        updateChartResult.setExecMessage("execMessage");
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            log.error("更新图表失败状态失败" + chartId + "," + execMessage);
        }
    }


}

    
    
